package cn.chenxinjie.hrm.filter;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author 陈鑫杰
 * @date 2022/3/21 12:35
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 根据手机号去数据库查询用户的权限信息
        String phone = (String) authentication.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        // 把用户的权限信息封装进SmsAuthenticationToken里面
        SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
        // 父类的参数Object details
        //smsAuthenticationToken.setDetails(userDetails);
        return smsAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class
                .isAssignableFrom(authentication));
    }
}
